﻿using Microsoft.Win32;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace installtool
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Install();
        }
        string manifestpath;
        string exepath;
        bool exeexists;
        void PrepareValues()
        {
            var installpath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
            listBox1.Items.Add("安装程序路径;" + installpath);
            manifestpath = System.IO.Path.Combine(installpath, "localfolder_manifest.json");
            listBox1.Items.Add("manifest路径;" + manifestpath);
            exepath = System.IO.Path.Combine(installpath, "net40", "localfolder.exe");
            listBox1.Items.Add("native plugin路径;" + exepath);
            exeexists = System.IO.File.Exists(exepath);
            listBox1.Items.Add("native plugin=" + exeexists);
            button1.Enabled = exeexists;
        }
        void Install()
        {
            //生成manifest
            JObject json = new JObject();
            json["name"] = "com.lighttool.localfolder";
            json["description"] = "操作本地硬盘目录的扩展工具";
            json["path"] = exepath;
            json["type"] = "stdio";
            var origins = new JArray();
            origins.Add("chrome-extension://"+textBox1.Text+ "/");
            json["allowed_origins"] = origins;
            var manstr = json.ToString();
            System.IO.File.Delete(manifestpath);
            System.IO.File.WriteAllText(manifestpath, manstr, System.Text.Encoding.UTF8);
            //写入注册表
            RegistryKey key = Registry.CurrentUser;
            string pluginname = "com.lighttool.localfolder";
            RegistryKey rkOpen = key.OpenSubKey("SOFTWARE\\Google\\Chrome\\NativeMessagingHosts\\" + pluginname, true);
            rkOpen.SetValue("", manifestpath, RegistryValueKind.String);
            rkOpen.Close();

            MessageBox.Show("安装成功");
            Application.Exit();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            PrepareValues();
        }
    }
}
